﻿using System;
using UnityEngine;

namespace GameFrameWork
{

    /// <summary>
    /// 复用列表控制器
    /// </summary>
    public abstract class UIReuseItemCtrl : IUIReuseItemCtrl
    {
        /// <summary>
        /// 下标
        /// </summary>
        protected int Index => (this as IUIReuseItemCtrl).index;
        /// <summary>
        /// 用户自定义数据
        /// </summary>
        protected object UserData => (this as IUIReuseItemCtrl).userDataGetter.userData;
        /// <summary>
        /// 是否选中
        /// </summary>
        protected bool IsSelected => (this as IUIReuseItemCtrl).isSelected;
        /// <summary>
        /// 资源加载模块
        /// </summary>
        protected IResModule Res => (this as IUIReuseItemCtrl).resModule;
        /// <summary>
        /// Item的RectTransform (只读: 由于Item是复用, 禁止作为ReuseItemCtrl成员)
        ///     * 动态Item可在OnRefresh回调中设置其大小
        /// </summary>
        protected RectTransform RectTransform => (this as IUIReuseItemCtrl).rectTransform;
        /// <summary>
        /// 显示回调
        /// </summary>
        protected virtual void OnEnable() { }
        /// <summary>
        /// 隐藏回调
        /// </summary>
        protected virtual void OnDisable() { }
        /// <summary>
        /// 触发刷新时回调
        /// </summary>
        protected virtual void OnRefresh() { }

        #region 框架Call

        int IUIReuseItemCtrl.index { get; set; }
        IUserDataGettable IUIReuseItemCtrl.userDataGetter { get; set; }
        IResModule IUIReuseItemCtrl.resModule { get; set; }
        bool IUIReuseItemCtrl.isSelected { get; set; }
        RectTransform IUIReuseItemCtrl.rectTransform { get; set; }

        void IUIReuseItemCtrl.Enable()
        {
            try
            {
                OnEnable();
            }
            catch (Exception e)
            {
                Debug.LogError($"{GetType().FullName}.OnEnable Exception: {e.Message}\nStackTrace: {e.StackTrace}");
            }
        }

        void IUIReuseItemCtrl.Disable()
        {
            try
            {
                OnDisable();
            }
            catch (Exception e)
            {
                Debug.LogError($"{GetType().FullName}.OnDisable Exception: {e.Message}\nStackTrace: {e.StackTrace}");
            }
        }

        void IUIReuseItemCtrl.Refresh()
        {
            try
            {
                OnRefresh();
            }
            catch (Exception e)
            {
                Debug.LogError($"{GetType().FullName}.OnRefresh Exception: {e.Message}\nStackTrace: {e.StackTrace}");
            }
        }
        #endregion
    }
}

